package com.chinadrtv.batch.admin.controller.ozing;

import com.chinadrtv.batch.admin.service.OzingCardBatchService;
import com.chinadrtv.batch.admin.util.Constants;
import com.chinadrtv.user.model.*;
import com.chinadrtv.user.service.ozing.OzingService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OzingCardMgrController {
    private Log log = LogFactory.getLog(OzingCardMgrController.class.getName());

    private final SimpleDateFormat ymd_sf = new SimpleDateFormat("yyyy-MM-dd");
    private final SimpleDateFormat ymdhms_sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private OzingService ozingService;

    @Autowired
    private OzingCardBatchService ozingCardBatchService;

    public void setOzingCardBatchService(OzingCardBatchService ozingCardBatchService) {
        this.ozingCardBatchService = ozingCardBatchService;
    }

    public void setOzingService(OzingService ozingService) {
        this.ozingService = ozingService;
    }

    @RequestMapping(value = "/ozing/cards", method = RequestMethod.GET)
    public String cards() {
        return "/ozing/cards";
    }

    @RequestMapping(value = "/ozing/card", method = RequestMethod.GET)
    public String card(@RequestParam(required = true) String cardId, ModelMap modelMap) {
        UserOzingCard userCard = ozingService.getUserCardByCardId(cardId);
        modelMap.put("userCard", userCard);
        return "/ozing/card";
    }

    @RequestMapping(value = "/ozing/cards.json", method = RequestMethod.GET)
      public String cardsJson(@RequestParam(required = false, defaultValue = "0") int start_index,
                              @RequestParam(required = false, defaultValue = "50") Integer num_per_page,
                              @RequestParam(required = false, defaultValue = "id") String sort,
                              @RequestParam(required = false, defaultValue = "desc") String dir,
                                 @RequestParam(required = false) String cardType, @RequestParam(required = false) String cardId,
                                 @RequestParam(required = false) String cardPassword, @RequestParam(required = false) String activeStartDate,
                                 @RequestParam(required = false) String activeEndDate, @RequestParam(required = false) String startAddedDate,
                                 @RequestParam(required = false) String endAddedDate,
                                 @RequestParam(required = false) String cardStatus,
                                 @RequestParam(required = false) String agent,
                                 @RequestParam(required = false) Long batchId,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException, ParseException {
        Map searchParams = new HashMap<String, Object>();
        if (cardType != null && cardType.equalsIgnoreCase("PAID")) {
            searchParams.put("cardType", CardType.PAID);
        } else if (cardType != null && cardType.equalsIgnoreCase("GIFT")) {
            searchParams.put("cardType", CardType.GIFT);
        }
        Date activeStartDate_ = null;
        Date activeEndDate_ = null;
        if (activeStartDate != null && !activeStartDate.trim().equals("")) {
            activeStartDate_ = ymd_sf.parse(activeStartDate);
        }
        if (activeEndDate != null && !activeEndDate.trim().equals("")) {
            activeEndDate_ = ymd_sf.parse(activeEndDate);
        }
        if (cardId != null && !cardId.equals("")) searchParams.put("cardId", cardId);
        if (cardPassword != null && !cardPassword.equals("")) searchParams.put("cardPassword", cardPassword);
        if (cardStatus != null && !cardStatus.equals("")) searchParams.put("cardStatus", cardStatus);
        if (agent != null && !agent.equals("")) searchParams.put("agent", agent);
        if (batchId != null && !batchId.equals("")) searchParams.put("batchId", batchId);
        List<OzingCard> ozingCards = ozingService.getOzingCardPaginatedList(Integer.valueOf(start_index), Integer.valueOf(num_per_page), searchParams, activeStartDate_, activeEndDate_, sort, dir);

        JSONArray jsonArray = new JSONArray();
        for (OzingCard ozingCard : ozingCards) {
            JSONObject jsonObject = ozingCard.toJson();
            jsonArray.put(jsonObject);
        }

        int totalRecords = ozingService.getOzingCardCount(searchParams, activeStartDate_, activeEndDate_);
        response.setContentType("text/json; charset=UTF-8");
        response.getWriter().write("{\"records\":" + jsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index + ",\"sort\":\"" + sort + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }

    @RequestMapping(value = "/admin/cards/status", method = RequestMethod.GET)
    public String cardsStatus(@RequestParam String[] cardIds, @RequestParam String status, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = getCurrentUser(request);
       ozingService.updateCardsStatus(cardIds, status, user);
        response.setContentType("text/json");
        response.getWriter().print("{\"delete\":\"true\"}");
        return null;
    }

    @RequestMapping(value = "/admin/cards/agent", method = RequestMethod.GET)
    public String cardsAgent(@RequestParam String[] cardIds, @RequestParam String agent, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = getCurrentUser(request);
       ozingService.updateCardsAgent(cardIds, agent, user);
        response.setContentType("text/json");
        response.getWriter().print("{\"delete\":\"true\"}");
        return null;
    }


    @RequestMapping(value = "/ozing/card/job", method = RequestMethod.GET)
    public String generateCards(HttpServletRequest request, HttpServletResponse response) {
        return "/ozing/generate_card_job";
    }

    @RequestMapping(value = "/ozing/card/jobs.json", method = RequestMethod.GET)
    public String paidCardJobs(@RequestParam(defaultValue = "0") String start_index,
                               @RequestParam(defaultValue = "8") String num_per_page,
                               HttpServletResponse response) throws ParseException, IOException, JSONException {
        JSONArray jsonArray = new JSONArray();
        int totalRecords = 0;

        Map<String, String> searchParaMap = new HashMap<String, String>();
        List<OzingCardBatch> ozingCardBatchList = ozingCardBatchService.getPaginatedList(Integer.valueOf(start_index), Integer.valueOf(num_per_page), searchParaMap);
        for (OzingCardBatch ozingCardBatch : ozingCardBatchList) {
            JSONObject jsonObject = ozingCardBatch.toJson();

            jsonArray.put(jsonObject);
        }
        totalRecords = ozingCardBatchService.count(searchParaMap);


        response.setContentType("text/json; charset=UTF-8");
        response.getWriter().write("{\"records\":" + jsonArray.toString() + ",\"totalRecords\":" + totalRecords + ",\"startIndex\":" + start_index + " }");

        return null;
    }

    @RequestMapping(value = "/ozing/card/job.json", method = RequestMethod.GET)
    public String paidCardJob( @RequestParam(required = true) String batchId,
                              HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException, JSONException {
        OzingCardBatch ozingCardBatch = ozingCardBatchService.get(Long.valueOf(batchId));
        if (ozingCardBatch == null) {
            ozingCardBatch = new OzingCardBatch();
        }

        response.setContentType("text/json; charset=UTF-8");
        JSONObject jsonObject = ozingCardBatch.toJson();
        response.getWriter().write(jsonObject.toString());
        return null;
    }

    @RequestMapping(value = "/ozing/card/batches", method = RequestMethod.GET)
    public String cardEntity(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap) {

        List<OzingCardBatch> ozingCardBatchList = ozingCardBatchService.getAllBatchs();
        modelMap.put("batches", ozingCardBatchList);

        return "/ozing/card_batches";
    }

    @RequestMapping(value = "/ozing/card/wzz.json", method = RequestMethod.GET)
    public String cardEntityJson(@RequestParam(defaultValue = "0") String start_index, @RequestParam(defaultValue = "10") String num_per_page,
                                 @RequestParam(required = false) String batchId,
                                 HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        JSONArray jsonArray = new JSONArray();
        List<OzingCard> ozingCards = ozingService.getOzingCardListByBatch(Integer.valueOf(start_index), Integer.valueOf(num_per_page), Long.valueOf(batchId));

        for (OzingCard ozingCard : ozingCards) {
            JSONObject jsonObject = ozingCard.toJson();
            jsonArray.put(jsonObject);
        }

        int totalRecords = ozingService.countOzingCardByBatch(Long.valueOf(batchId));
        response.setContentType("text/json; charset=UTF-8");
        response.getWriter().write("{\"records\":" + jsonArray.toString() + ",\"totalRecords\":" + totalRecords + ",\"startIndex\":" + start_index + "}");
        return null;

    }

    private User getCurrentUser(HttpServletRequest request) {
        SecurityContext ctx = (SecurityContext) request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return (User) ctx.getAuthentication().getPrincipal();
    }

}
